//
//  ListController.swift
//  plane
//
//  Created by tong on 16/3/28.
//  Copyright © 2016年 tong. All rights reserved.
//


import UIKit
import Kingfisher
import Eelay
import JoLoading
import RTRootNavigationController

extension UIViewController{
    
    @objc public static var currentWindow:UIWindow?{
        guard let rootCtr = UIWindow.topWindow else {return nil}
        return rootCtr
    }
    
    @objc public static var current:UIViewController?{
        guard let rootCtr = UIWindow.topWindow?.rootViewController else {return nil}
//        guard let rootCtr = UIApplication.shared.delegate?.window??.rootViewController else {
//            return nil
//        }
                
        return UIViewController.getCurrentCtrFrom(rootVC: rootCtr)
    }
    
    public static func getCurrentCtrFrom( rootVC:UIViewController?)->UIViewController?{
                
        var rootCtr = rootVC
        
        var currentVC:UIViewController? = nil
        
        if rootCtr?.presentedViewController != nil {
            
            while rootCtr?.presentedViewController != nil {
                
                rootCtr = rootCtr?.presentedViewController
            }
        }
       
        if let tab = rootCtr as? UITabBarController{
            currentVC = UIViewController.getCurrentCtrFrom(rootVC: tab.selectedViewController)
        }
        else if let nav = rootCtr as? UINavigationController{
            currentVC = UIViewController.getCurrentCtrFrom(rootVC: nav.visibleViewController)
        }else{
            if let root = rootCtr{
                if root.children.count > 0{
                    currentVC = root.children.last
                    
                    if var list = currentVC?.children{
                        while list.count > 0 {
                            currentVC = currentVC?.children.last
                            if let ls = currentVC?.children{
                                list = ls
                            }
                        }
                    }
                }
                else{
                    currentVC = rootCtr
                }
            }
        }
        return currentVC
    }
}



//#pragma mark   - 获取当前控制器
////获取当前屏幕显示的viewcontroller
//
//+ (UIViewController *)getCurrentViewController
//{
//    //iOS9之后获取keywindow的方法变为
//    UIWindow *keyWindow =[[UIApplication sharedApplication].delegate window];
//
//    UIViewController *rootViewController = keyWindow.rootViewController;
//
//    UIViewController *currentVC = [[self class] getCurrentVCFrom:rootViewController];
//
//    return currentVC;
//}
//
//+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
//{
//    UIViewController *currentVC;
//    if ([rootVC presentedViewController]) {
//        // 视图是被presented出来的
//        while ([rootVC presentedViewController]) {
//            rootVC = rootVC.presentedViewController;
//        }
//    }
//    if ([rootVC isKindOfClass:[UITabBarController class]]) {
//        // 根视图为UITabBarController
//        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
//
//    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
//
//        // 根视图为UINavigationController
//
//        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
//
//    }else {
//
//        // 根视图为非导航类
//
//        if (rootVC.childViewControllers.count >0) {
//
//            currentVC = rootVC.childViewControllers.lastObject;
//
//            while (currentVC.childViewControllers.count > 0) {
//
//               // NSLog(@"childViewControllers:%@",currentVC.childViewControllers);
//
//                currentVC = currentVC.childViewControllers.lastObject;
//
//            }
//
//            NSLog(@"获取到当前的控制器:lastCurrentVC:%@",currentVC);
//
//            return currentVC;
//
//        }else
//        {
//
//            currentVC = rootVC;
//
//        }
//
//    }
//    return currentVC;
//}
//
//@end



public typealias ClickAction = (_:NSMutableDictionary,_:Any)->Void
public class _KitClick<Kit>{
    var block:(_:Kit)->Void
    public init(_ action:@escaping(_:Kit)->Void) {
        self.block = action
    }
}
public class _Click{
    public var block:(_:UIViewController)->Void
    public init(_ action:@escaping(_:UIViewController)->Void) {
        self.block = action
    }
}


public class _ASClick{
    public var block:(_:ASButtonNode)->Void
    public init(_ action:@escaping(_:ASButtonNode)->Void) {
        self.block = action
    }
}

extension TP {
    public typealias selector = [String:Any]
    public typealias section = [[[String:Any]]]
    public typealias options = [[String:Any]]
}


public enum AppearStatus{
    case willAppear
    case didAppear
    case didDisappear
    case willDisappear
    case none
}



extension UITableView
{
    public func buildDynamicHeight(height:CGFloat=UIScreen.main.bounds.height){
        self.separatorInset = UIEdgeInsets.zero
        self.layoutMargins = UIEdgeInsets.zero
        
        self.estimatedRowHeight = height
        self.rowHeight = UITableView.automaticDimension
        self.estimatedSectionHeaderHeight = 0
        self.sectionHeaderHeight = UITableView.automaticDimension
        
        self.sectionFooterHeight = 0
        self.sectionHeaderHeight = 0
        //        self.separatorStyle = .None
        self.hidenMoreLine()
    }
}

extension UITableView
{
    public func hidenMoreLine()
    {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        self.tableFooterView = view
        //
        //        let back = UIView()
        //        back.backgroundColor = UIColor.back_color()
        //        self.backgroundView = back;
    }
    public func setBkView(hex :String="#F3F4F5")
    {
        let back = UIView()
        back.backgroundColor = UIColor(shex: hex)
        self.backgroundView = back
    }
    
    public func setImgBack(image_name:String="img_login") {
        let imgV = UIImageView()
        imgV.image = UIImage(named: image_name)
        self.backgroundView = imgV
    }
    public func alignmentToLeft()
    {
        self.separatorInset = UIEdgeInsets.zero
        self.layoutMargins = UIEdgeInsets.zero
        
    }
    
    public func load(sections:TP.section=TP.section(),selector:TP.selector)
    {
        buildDynamicHeight(height: 100)
        if sections.count == 0{
            let section1:TP.section = [[]]
            let model =  CellSelector.createModel(sections: section1)
            self.model =  model
        }
        else
        {
            let model =  CellSelector.createModel(sections: sections)
            self.model =  model
        }
        
        self.cell_selector = selector
    }
    
    
}


//public enum AppearStatus
//{
//    case disappearing
//    case disappeared
//    case appeared
//    case appearing
//    case none
//}


extension TypeInitController
{
    public static var autoClearMemoryCache = false
    
}

extension UIViewController{
    public enum Notice:String,NotifyType {
        
        case updateLink = "updateLink"
        
        public var name: Notification.Name{
            switch self {
            case .updateLink:
                return "UIViewController.updateLink".notice_name
            }
            //            return "JoUser.\(Notice.self)\(self.rawValue)".notice_name
        }
    }
    
    
}

public protocol LinkOnlineRefreshProtocol{
    var __link:String{get set}
    func checkIfNeedRefresh(link:String) -> Bool
    func refreshLinkView()
}

extension UIView{
    @objc public var owner_controller:UIViewController?{
        get{
            return _mo_owner_controller
        }
        set{
            self._mo_owner_controller = newValue//和mo.controller 属性有关
        }
    }
   
}

open class TypeInitController:UIViewController,MoAtrributeProtocol,MoRequestTask,LoadingPresenter,EeTopStyleSupport,LinkOnlineRefreshProtocol
{
    
    @objc public var mo:MoAtrribute{
        get{
            if let obj = objc_getAssociatedObject(self, &MoAtrributeProtocolKeys.mo) as? MoAtrribute
            {
                return obj
            }
            let newValue = MoAtrribute()
            
            newValue.ower = self
            objc_setAssociatedObject(self, &MoAtrributeProtocolKeys.mo, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return newValue
        }
        set{
            
            
            self.mo_model_willSet(new: newValue.model)
            self.mo_detail_willSet(new: newValue.detail)
            
            if let obj = objc_getAssociatedObject(self, &MoAtrributeProtocolKeys.mo) as? MoAtrribute
            {
                self.mo_model_relase(current: obj.model)
                self.mo_detail_relase(current: obj.detail)
            }
            
            objc_setAssociatedObject(self, &MoAtrributeProtocolKeys.mo, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            newValue.ower = self
            self.mo_model_reload()
            self.mo_detail_reload()
        }
    }
    open func mo_change_localizable(obj: Any?) {
        
    }
    
    public var __link: String = "undefined"
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        top_style.playUp()
    }
    
    open func checkIfNeedRefresh(link: String) -> Bool {
        return link == __link
    }
    
    open func refreshLinkView() {
        mo_request_send()
    }
    
    
    open var initTopStyle: EeTopStyle{
        get{
            return EeTopStyle.default
        }
    }
    
    open var LoadingPresenterBg: UIView{
        get{
            return self.view
        }
    }
    
    open var LoadingClass:JoLoading.Type{
        get{
            return LoadingPresenterDefautLoadingClass
        }
    }
    
    open var loadingPresenterInset: UIEdgeInsets{
        get{
            return .zero
        }
    }
    
    
    public var rootNavigationController:UINavigationController?{
        get{
            if let n = self.navigationController as? RTContainerNavigationController{
                return n.navigationController
            }
            return self.navigationController
        }
    }
    
    
    
    
    public static var IDActiveAction:((UIViewController,String,NSMutableDictionary) -> Void) = {_,_,_ in}
    
    public var appearStatus:AppearStatus = .none{
        didSet{
            
        }
    }
    
    open func changeAppearStatus(status:AppearStatus){}
        
    public var presentType:NavPresentType = .defaultPush
    
    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if (self.navigationController as? EeNavigationController) != nil{
            bringEeNavbar()
        }
    }
    
    
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.appearStatus = .didAppear
        
//        _ = TP.bottomLayoutGuide
        
    }
    
    
    open override func loadView() {
        super.loadView()
        
        
    }
    
    open override func viewDidLoad() {
        

        switch EeTopStyle.mode{
        case .rtnav:
            top_style = initTopStyle
        default:
            break
        }
        __notice.add(task: (TP.Notice.localizableDidChange,{[weak self] n in
            self?.mo_change_localizable(obj: nil)
        }))
        super.viewDidLoad()
        switch self.presentType {
        case .navRootPresent:
            //            let backBt = UIButton()
            let bundle = Bundle(for: ListController.self)
            let canleImg = UIImage(named: "delete_tag", in: bundle, compatibleWith: nil)
            let bt = UIBarButtonItem(image: canleImg, style: .plain, target: self, action: #selector(dismissAction))
            self.navigationItem.leftBarButtonItem = bt
        default:
            break
        }
        view._mo_owner_controller = self//和mo.controller 属性有关
        
        
    }
    
    @objc open func dismissAction(){
        switch self.presentType {
        case .navRootPresent:
            self.navigationController?.dismiss(animated: true, completion:nil)
        case .backSkip(let step):
            self.popController(step)
        default:
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.appearStatus = .willAppear
//        if validPresent
//        {
//            __controller = self
//        }
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.appearStatus = .didDisappear
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.appearStatus = .willDisappear
    }
    
    required public init()
    {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .fullScreen

    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.modalPresentationStyle = .fullScreen

    }
    open func mo_set_controller(controller: UIViewController) {
        
    }
    
    
    open func mo_model_reload() {
        
    }
    
    open func mo_detail_reload() {
        
    }
    
    open func mo_request_send() {
        
    }
    
    
    open func mo_request_load(obj: Any) {
        
    }
    
    open func mo_request_alert(msg: String, title: String, bt_title: String) {
        weak var wself = self
        if bt_title.len < 1
        {
            loadingV.show(message: msg, title: title)
            return
        }
        self.loadingV.handle(message: msg, title: title, button: bt_title, handAction: {
            switch bt_title.escapeHeadTailSpace(){
            case "登录".loc,"立即登录".loc:
                EeAuthControl.getUser(finish_block: { (success, msg, user) in
                    
                })
            case "重试".loc,"刷新".loc:
                wself?.loadingV.loading()
                wself?.mo_request_send()
            default:
                wself?.loadingV.loading()
                wself?.mo_request_send()
            }
            
        })
    }
    
    open override var shouldAutorotate: Bool{
        get{
            return false
        }
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
        
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return .portrait
    }

    deinit {
//        print("===OOOIIIIII|-------------------",self)
    }
    
    
}


open class ListController: TypeInitController,TableVConfig {
    
    public var tableView:UITableView = UITableView(frame: [0], style: .plain)
    public var so_constrains = [NSLayoutConstraint]()
    public var edegs:(top:CGFloat,left:CGFloat,bottom:CGFloat,right:CGFloat) = (0,0,0,0)
    
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    required public init() {
        super.init()
    }
    
    public func load(sections:TP.section,selector:TP.selector)
    {
        tableView.load(sections: sections, selector: selector)
    }
    
    public var contentInsetView: UIScrollView? {
        get{
            return self.tableView
        }
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor._tableBackground
        layTable(tableView: tableView)
        tableView.hidenMoreLine()
        self.configTables(tables: tableView)        
    }
    
    open func layTable(tableView:UIView)
    {
        jo_contentView.eelay = [
            [tableView,[ee.T.L.B.R]]
        ]
    }
    
    
    
    
    public func remove_constains()
    {
        self.jo_contentView.removeConstraints(self.so_constrains)
    }
    
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return TP.TableVConfigMethod.tableView(owner: self, tableView, cellForRowAt: indexPath)
    }
    //    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //        return TP.TableVConfigMethod.tableView(owner: self, tableView, cellForRowAt: indexPath)
    //    }
    
    //    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //        return TP.TableVConfigMethod.tableView(owner: self, tableView, cellForRowAt: indexPath)
    //    }
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        TypeInitController.IDActiveAction(self,actionID,model)
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero
    }
    
    deinit {
        if TypeInitController.autoClearMemoryCache
        {
            KingfisherManager.shared.cache.clearMemoryCache()
        }
    }
    
}




